<script setup lang="ts">
import Taro, { getCurrentInstance, showToast, showLoading, hideLoading, navigateBack } from '@tarojs/taro';
import { reactive, ref, onMounted, computed } from 'vue';
import { useAddrStore, useAuthStore } from '@/store';
import { useNurseUser, use_hospital_dept_bed } from '@/service';
import { useGetAuthInfo } from '@/hooks';
import { SUCCESS_MSG_DURATION } from '@/constants';
import { storeToRefs } from 'pinia';
import { request } from '@/service/request';

const {
    router: {
        params: { id }
    }
}: any = getCurrentInstance();

// definePageConfig({
//     navigationBarTitleText: id ? '设置地址' : '新增地址'
// });

Taro.setNavigationBarTitle({
    title: id ? '设置地址' : '新增地址'
});

const { getHospitalList, getbedList } = use_hospital_dept_bed();

// const { getLocation } = useweChat_location_service()

const { edit } = useNurseUser();

const { nurseUser } = storeToRefs(useAuthStore());

const { nurseUserAddrList } = nurseUser.value;

const { getProvince, getCity, getCountry } = useAddrStore();

const formData = ref<any>({
    name: '',
    phone: '',
    area: '',
    areaName: '',
    address: '',
    isDefault: '',
    record: '',
    hospital: '',
    hospitalName: '',
    dept: '', // 部门ID
    deptName: '', // 部门名称
    depart: '', // 科室ID
    departName: '', // 科室名称
    projectid: '', // 项目组ID
    projectname: '', // 项目组名称
    bed: '',
    bedName: '',
    id: '',
    longitude: '',
    latitude: '',
    type: '1' // '1' 表示院内地址，'2' 表示居家地址，默认为院内地址
});

const editIndex = ref(nurseUserAddrList?.findIndex(item => item.id == id));

if (editIndex?.value !== undefined && id && nurseUserAddrList) {
    const editData = nurseUserAddrList[editIndex.value];
    console.log("editData", editData);
    // 编辑模式下，直接使用 editData 中的所有字段，包括 departName 和 projectname
    formData.value = { 
        ...editData,
        type: (editData as any).type || '1', // 如果没有type字段，默认为院内地址
        // 确保 departName 和 projectname 字段正确映射
        departName: (editData as any).departName || '',
        projectname: (editData as any).projectname || ''
    };
}

// 计算是否为居家地址
const isHomeAddress = computed(() => formData.value.type === '2');

// 动态生成医院字段的验证规则
const hospitalRules = computed(() => {
    return isHomeAddress.value 
        ? [{ required: false, message: '' }]
        : [{ required: true, message: '请选择医院' }];
});

// 动态生成部门字段的验证规则
const deptRules = computed(() => {
    return isHomeAddress.value 
        ? [{ required: false, message: '' }]
        : [{ required: true, message: '请选择部门' }];
});

// 动态生成科室字段的验证规则
const departRules = computed(() => {
    return isHomeAddress.value 
        ? [{ required: false, message: '' }]
        : [{ required: true, message: '请选择科室' }];
});

// 动态生成项目组字段的验证规则
const projectRules = computed(() => {
    return isHomeAddress.value 
        ? [{ required: false, message: '' }]
        : [{ required: true, message: '请选择项目组' }];
});

// 动态生成床号字段的验证规则
const bedRules = computed(() => {
    return isHomeAddress.value 
        ? [{ required: false, message: '' }]
        : [{ 
            required: true, 
            message: '请输入床号',
            validator: (value: string) => {
                // 允许手动输入或选择床号，只要 bedName 有值即可
                return Boolean(value && value.trim());
            }
        }];
});

// 根据ID和父级ID获取名称
const getNameById = async (itemId: string, parentId: string) => {
    if (!itemId || !parentId) return '';
    try {
        const res = await request.get(
            '/sys/sysDepart/queryDepartTreeSync',
            { pid: parentId },
            { useErrMsg: true }
        );
        
        let records = [];
        if (res.success && (res.success as any).records) {
            records = (res.success as any).records;
        } else if (res.success && Array.isArray(res.success)) {
            records = res.success;
        }
        
        const item = records?.find((item: any) => (item.id || item.key) == itemId);
        return item ? (item.title || item.name || '') : '';
    } catch (error) {
        return '';
    }
};

onMounted(async () => {
    // 编辑模式下，如果数据中已经有名称字段，直接使用；如果没有名称但有ID，才通过API获取
    if (id && editIndex.value !== undefined) {
        // 如果有部门ID但没有部门名称，获取部门名称
        if (formData.value.dept && !formData.value.deptName && formData.value.hospital) {
            const name = await getNameById(formData.value.dept, formData.value.hospital);
            if (name) {
                formData.value.deptName = name;
            }
        }
        
        // 如果有科室ID但没有科室名称，获取科室名称
        // 注意：如果 editData 中已经有 departName，直接使用，不需要通过API获取
        if (formData.value.depart && !formData.value.departName && formData.value.dept) {
            const name = await getNameById(formData.value.depart, formData.value.dept);
            if (name) {
                formData.value.departName = name;
            }
        }
        
        // 如果有项目组ID但没有项目组名称，获取项目组名称
        // 注意：如果 editData 中已经有 projectname，直接使用，不需要通过API获取
        if (formData.value.projectid && !formData.value.projectname && formData.value.depart) {
            const name = await getNameById(formData.value.projectid, formData.value.depart);
            if (name) {
                formData.value.projectname = name;
            }
        }
    }
});

const ruleForm = ref<any>(null);

const select = reactive({ text: '', value: '' });

const defaultChange = () => nurseUserAddrList.forEach(item => (item.isDefault = false));

const submit = async () => {
    const { valid } = await ruleForm.value.validate();

    if (!valid) return;

    showLoading({ title: '正在保存...' });
    if (id && editIndex.value !== undefined && nurseUserAddrList) {
        nurseUserAddrList[editIndex.value] = { ...formData.value };
    } else {
        nurseUserAddrList?.push({
            ...formData.value,
            userId: nurseUser.value.id
        });
    }
    const data = { id: nurseUser.value.id, nurseUserAddrList };

    const { error } = await edit(data);

    hideLoading();

    if (!error) {
        showToast({
            title: '保存成功',
            icon: 'success',
            duration: SUCCESS_MSG_DURATION
        });
        setTimeout(() => {
            navigateBack();
        }, 1200);
        useGetAuthInfo();
    }
};
const areaModule: any = reactive({
    show: false,
    province: getProvince,
    city: [{}],
    country: [{}],
    town: [],
    showArea: () => {
        areaModule.show = !areaModule.show;
        if (areaModule.show) {
            select.text = '';
            select.value = '';
        }
    },
    onChange: (item: any) => {
        const { custom, next, value } = item;

        switch (custom) {
            case 'province':
                const city = getCity.filter(item => item.pid == value.id);
                areaModule.city = city;
                break;
            case 'city':
                const country = getCountry.filter(item => item.pid == value.id);
                areaModule.country = country;
                break;
            default:
                break;
        }
        select.text += value.name;
        select.value += `${value.id}-`;
        const name = areaModule[next];
        if (!name?.length) {
            areaModule.show = false;
            formData.value.areaName = select.text;
            formData.value.area = select.value;
        }
    }
});

// 根据orgCode获取医院ID
const getHospitalIdByOrgCode = async (orgCode: string) => {
    return new Promise((resolve, reject) => {
        request.get('/sys/sysDepart/getDepartName', {
            orgCode
        }, {
            useErrMsg: true
        }).then(res => {
            const id = (res.success as any)?.id;
            if (id) {
                resolve(id);
            } else {
                reject(new Error('未获取到医院ID'));
            }
        }).catch(error => {
            reject(error);
        });
    });
};

const hospitalModule = reactive({
    show: false,
    showHospital: () => {
        hospitalModule.show = !hospitalModule.show;

        if (hospitalModule.show) {
            formData.value.hospital = '';
            formData.value.hospitalName = '';
            // 清空下级选择
            formData.value.dept = '';
            formData.value.deptName = '';
            formData.value.depart = '';
            formData.value.departName = '';
            formData.value.projectid = '';
            formData.value.projectname = '';
            formData.value.bed = '';
            formData.value.bedName = '';
        }
    },
    onChange: async (items: any) => {
        if (items.length == 0) return;
        const item = items[items.length - 1];
        
        // 设置医院名称
        formData.value.hospitalName = item.title;
        
        // 根据orgCode获取医院ID
        if (item.sysOrgCode) {
            try {
                const hospitalId = await getHospitalIdByOrgCode(item.sysOrgCode);
                formData.value.hospital = hospitalId as string;
                
                // 清空下级选择
                formData.value.dept = '';
                formData.value.deptName = '';
                formData.value.depart = '';
                formData.value.departName = '';
                formData.value.projectid = '';
                formData.value.projectname = '';
                formData.value.bed = '';
                formData.value.bedName = '';
                
            } catch (error) {
                // 如果获取ID失败，使用原始key作为备用
                formData.value.hospital = item.key;
            }
        } else {
            // 如果没有orgCode，使用原始key
            formData.value.hospital = item.key;
        }
        
        hospitalModule.show = false;
    },
    lazyLoad: async (pid: string) => {
        const { error, success } = await getHospitalList(pid);
        if (!error && success?.length > 0) {
            const list = success?.map((item: any) => {
                return {
                    value: item,
                    text: item.title
                };
            });
            return list;
        }
        return [];
    }
});

// 部门选择器模块
const departmentModule = reactive({
    show: false,
    options: [],
    showSelector: async () => {
        departmentModule.show = !departmentModule.show;
        if (departmentModule.show) {
            await departmentModule.onRefreshOptions();
        }
    },
    onRefreshOptions: async () => {
        const hospitalId = formData.value.hospital;
        if (!hospitalId) {
            showToast({
                title: '请先选择医院',
                icon: 'none',
                duration: 2000
            });
            departmentModule.options = [];
            return;
        }
        
        try {
            const res = await request.get(
                '/sys/sysDepart/queryDepartTreeSync',
                { pid: hospitalId },
                { useErrMsg: true }
            );
            
            let records = [];
            if (res.success && (res.success as any).records) {
                records = (res.success as any).records;
            } else if (res.success && Array.isArray(res.success)) {
                records = res.success;
            }
            
            const list = records?.map((item: any) => ({
                key: item.id || item.key,
                id: item.id || item.key,
                value: item.id || item.key,
                text: item.title || item.name,
                title: item.title || item.name,
                name: item.name
            })) || [];
            
            departmentModule.options = list;
        } catch (error) {
            departmentModule.options = [];
        }
    },
    onChange: (items: any) => {
        if (!items || items.length == 0) return;
        // basic-cascader 返回的是数组，取第一个元素（因为只有一级选择）
        const selectedValue = items[0];
        // selectedValue 是 value（id），需要从 options 中找到对应的完整对象
        const selectedOption = departmentModule.options.find((opt: any) => opt.value === selectedValue || opt.id === selectedValue || opt.key === selectedValue) as any;
        if (selectedOption) {
            formData.value.dept = selectedOption.id || selectedOption.key || selectedOption.value;
            formData.value.deptName = selectedOption.title || selectedOption.name || selectedOption.text;
        } else {
            // 如果找不到，尝试直接从 items 中获取
            const item = items[0];
            formData.value.dept = item?.id || item?.key || item?.value || selectedValue;
            formData.value.deptName = item?.title || item?.name || item?.text || '';
        }
        departmentModule.show = false;
        // 清空下级选择
        formData.value.depart = '';
        formData.value.departName = '';
        formData.value.projectid = '';
        formData.value.projectname = '';
        formData.value.bed = '';
        formData.value.bedName = '';
    }
});

// 科室选择器模块
const deptModule = reactive({
    show: false,
    options: [],
    showSelector: async () => {
        deptModule.show = !deptModule.show;
        if (deptModule.show) {
            await deptModule.onRefreshOptions();
        }
    },
    onRefreshOptions: async () => {
        const deptId = formData.value.dept; // 使用部门ID
        if (!deptId) {
            showToast({
                title: '请先选择部门',
                icon: 'none',
                duration: 2000
            });
            deptModule.options = [];
            return;
        }
        
        try {
            const res = await request.get(
                '/sys/sysDepart/queryDepartTreeSync',
                { pid: deptId },
                { useErrMsg: true }
            );
            
            let records = [];
            if (res.success && (res.success as any).records) {
                records = (res.success as any).records;
            } else if (res.success && Array.isArray(res.success)) {
                records = res.success;
            }
            
            const list = records?.map((item: any) => ({
                key: item.id || item.key,
                id: item.id || item.key,
                value: item.id || item.key,
                text: item.title || item.name,
                title: item.title || item.name,
                name: item.name
            })) || [];
            
            deptModule.options = list;
        } catch (error) {
            deptModule.options = [];
        }
    },
    onChange: (items: any) => {
        if (!items || items.length == 0) return;
        // basic-cascader 返回的是数组，取第一个元素（因为只有一级选择）
        const selectedValue = items[0];
        // selectedValue 是 value（id），需要从 options 中找到对应的完整对象
        const selectedOption = deptModule.options.find((opt: any) => opt.value === selectedValue || opt.id === selectedValue || opt.key === selectedValue) as any;
        if (selectedOption) {
            formData.value.depart = selectedOption.id || selectedOption.key || selectedOption.value;
            formData.value.departName = selectedOption.title || selectedOption.name || selectedOption.text;
        } else {
            // 如果找不到，尝试直接从 items 中获取
            const item = items[0];
            formData.value.depart = item?.id || item?.key || item?.value || selectedValue;
            formData.value.departName = item?.title || item?.name || item?.text || '';
        }
        deptModule.show = false;
        // 清空下级选择
        formData.value.projectid = '';
        formData.value.projectname = '';
        formData.value.bed = '';
        formData.value.bedName = '';
    }
});

// 项目组选择器模块
const projectModule = reactive({
    show: false,
    options: [],
    showSelector: async () => {
        projectModule.show = !projectModule.show;
        if (projectModule.show) {
            await projectModule.onRefreshOptions();
        }
    },
    onRefreshOptions: async () => {
        const departId = formData.value.depart; // 使用科室ID
        if (!departId) {
            showToast({
                title: '请先选择科室',
                icon: 'none',
                duration: 2000
            });
            projectModule.options = [];
            return;
        }
        
        try {
            const res = await request.get(
                '/sys/sysDepart/queryDepartTreeSync',
                { pid: departId },
                { useErrMsg: true }
            );
            
            let records = [];
            if (res.success && (res.success as any).records) {
                records = (res.success as any).records;
            } else if (res.success && Array.isArray(res.success)) {
                records = res.success;
            }
            
            const list = records?.map((item: any) => ({
                key: item.id || item.key,
                id: item.id || item.key,
                value: item.id || item.key,
                text: item.title || item.name,
                title: item.title || item.name,
                name: item.name
            })) || [];
            
            projectModule.options = list;
        } catch (error) {
            projectModule.options = [];
        }
    },
    onChange: (items: any) => {
        if (!items || items.length == 0) return;
        // basic-cascader 返回的是数组，取第一个元素（因为只有一级选择）
        const selectedValue = items[0];
        // selectedValue 是 value（id），需要从 options 中找到对应的完整对象
        const selectedOption = projectModule.options.find((opt: any) => opt.value === selectedValue || opt.id === selectedValue || opt.key === selectedValue) as any;
        if (selectedOption) {
            formData.value.projectid = selectedOption.id || selectedOption.key || selectedOption.value;
            formData.value.projectname = selectedOption.title || selectedOption.name || selectedOption.text;
        } else {
            // 如果找不到，尝试直接从 items 中获取
            const item = items[0];
            formData.value.projectid = item?.id || item?.key || item?.value || selectedValue;
            formData.value.projectname = item?.title || item?.name || item?.text || '';
        }
        projectModule.show = false;
        // 清空下级选择
        formData.value.bed = '';
        formData.value.bedName = '';
    }
});

const bedModule: any = reactive({
    show: false,
    columns: [],
    onRefreshColumns: async () => {
        const departId = formData.value.depart; // 使用科室ID
        if (!departId) {
            showToast({
                title: '请先选择科室',
                icon: 'none',
                duration: 2000
            });
            bedModule.columns = [];
            return;
        }

        const { error, success } = await getbedList(departId);

        if (!error && success?.length > 0) {
            const list = success?.map((item: any) => {
                return {
                    value: item,
                    text: item.name,
                    id: item.id,
                    name: item.name
                };
            });
            bedModule.columns = list;
        } else {
            bedModule.columns.length = 0;
        }
    },
    showBed: async () => {
        if (!formData.value.depart) {
            showToast({
                title: '请先选择科室',
                icon: 'none',
                duration: 2000
            });
            return;
        }
        bedModule.show = !bedModule.show;
        if (bedModule.show) {
            formData.value.bed = '';
            formData.value.bedName = '';
            await bedModule.onRefreshColumns();
        }
    },
    confirm: ({ selectedValue, selectedOptions }: any) => {
        const selected = selectedOptions?.[0] || selectedValue?.[0];
        if (selected) {
            formData.value.bed = selected.id || selected.value?.id;
            formData.value.bedName = selected.name || selected.text || selected.value?.name;
        }
        bedModule.show = false;
    }
});
onMounted(() => {
    // chooseLocation({
    //     success: function (res) {
    //         // res
    //     },
    //     fail: function (res) {
    //         // fail
    //     },
    // });
    // getLocation({
    //     type: 'gcj02', //返回可以用于 Taro.openLocation的经纬度
    //     success: function (res) {
    //         const latitude = res.latitude
    //         const longitude = res.longitude
    //         openLocation({
    //             latitude,
    //             longitude,
    //             scale: 18
    //         })
    //     }
    // })
});

// const getLocation = async () => {
//     Taro.getLocation({
//     type: 'wgs84', // 返回可以用于wx.openLocation的经纬度
//     success: function (res) {
//         const { latitude, longitude } = res;
//         // 当前位置的纬度
//         // 当前位置的经度
//     },
//     fail: function (err) {
//         // 获取位置失败
//     }
//     });
//  }

// 打开地图选择位置
const chooseLocation = async () => {
    try {
        let latitude;
        let longitude;
        Taro.getLocation({
            type: 'wgs84',
            // type: 'gcj02',
            success(res) {
                latitude = res.latitude;
                longitude = res.longitude;
                // 获取返回的位置
            }
        });
        const reschooseLocation = await Taro.chooseLocation({
            latitude, // 39.9,  // 默认纬度
            longitude // 116.4 // 默认经度
        });
        // 选择的位置
        formData.value.areaName = reschooseLocation.address;
        formData.value.area = reschooseLocation.address;
        formData.value.longitude = reschooseLocation.longitude;
        formData.value.latitude = reschooseLocation.latitude;
    } catch (err) {
        // 选择位置失败
        formData.value.areaName = '';
        formData.value.area = '';
    }
};
</script>
<template>
    <basic-layout>
        <!-- <custom-navbar :title="id ? '设置地址' : '新增地址'" show-left /> -->
        <view class="w-375px flex-col-center">
            <view class="w-360px">
                <nut-form ref="ruleForm" class="w-full" :model-value="formData">
                    <nut-form-item label="联系人" prop="name" required :rules="[{ required: true, message: '请填写联系人' }]">
                        <nut-input v-model="formData.name" placeholder="请输入联系人" type="text" />
                    </nut-form-item>
                    <nut-form-item label="联系电话" prop="phone" required :rules="[{ required: true, message: '请填写联系电话' }]">
                        <nut-input v-model="formData.phone" placeholder="请输入联系电话" type="text" />
                    </nut-form-item>
                    <nut-form-item label="地区" prop="area" required :rules="[{ required: true, message: '请选择地区' }]">
                        <!-- <nut-input v-model="formData.areaName" readonly placeholder="请选择地区" @click="areaModule.showArea"
                            type="text" /> -->

                        <nut-input v-model="formData.areaName" readonly placeholder="请选择地区" type="text"
                            @click="chooseLocation()" />

                        <!-- <nut-address v-model:visible="areaModule.show" :province="areaModule.province"
                            :city="areaModule.city" :country="areaModule.country" :town="areaModule.town"
                            @change="areaModule.onChange" custom-address-title="请选择所在地区"></nut-address> -->
                    </nut-form-item>
                    <nut-form-item label="详细地址" prop="address" required
                        :rules="[{ required: true, message: '请填写详细地址' }]">
                        <nut-input v-model="formData.address" placeholder="请输入详细地址" type="text" />
                    </nut-form-item>

                    <nut-form-item label="地址类型" prop="type" required :rules="[{ required: true, message: '请选择地址类型' }]">
                        <nut-radio-group v-model="formData.type" direction="horizontal">
                            <nut-radio label="1">院内地址</nut-radio>
                            <nut-radio label="2">居家地址</nut-radio>
                        </nut-radio-group>
                    </nut-form-item>

                    <nut-form-item label="医院" prop="hospital" :required="!isHomeAddress" :rules="hospitalRules">
                        <nut-input v-model="formData.hospitalName" readonly placeholder="请选择医院" type="text"
                            @click="hospitalModule.showHospital" />
                        <basic-hospital v-model:visible="hospitalModule.show" :lazy-load="hospitalModule.lazyLoad"
                            :title="formData.hospitalName || formData.defaultHospitalName" @change="hospitalModule.onChange" />
                    </nut-form-item>
                    <nut-form-item label="部门" prop="dept" :required="!isHomeAddress" :rules="deptRules">
                        <view class="w-full flex justify-between items-center">
                            <nut-input v-model="formData.deptName" readonly placeholder="请选择部门" type="text" />
                            <nut-button size="mini" type="default" @click="departmentModule.showSelector">选择部门</nut-button>
                        </view>
                        <basic-cascader v-model:visible="departmentModule.show" v-model:options="departmentModule.options"
                            :title-prefix="'当前部门'" :current-value="formData.deptName"
                            @change="departmentModule.onChange" />
                    </nut-form-item>
                    <nut-form-item label="科室" prop="depart" :required="!isHomeAddress" :rules="departRules">
                        <view class="w-full flex justify-between items-center">
                            <nut-input v-model="formData.departName" readonly placeholder="请选择科室" type="text" />
                            <nut-button size="mini" type="default" @click="deptModule.showSelector">选择科室</nut-button>
                        </view>
                        <basic-cascader v-model:visible="deptModule.show" v-model:options="deptModule.options"
                            :title-prefix="'当前科室'" :current-value="formData.departName"
                            @change="deptModule.onChange" />
                    </nut-form-item>
                    <nut-form-item label="项目组" prop="projectid" :required="!isHomeAddress" :rules="projectRules">
                        <view class="w-full flex justify-between items-center">
                            <nut-input v-model="formData.projectname" readonly placeholder="请选择项目组" type="text" />
                            <nut-button size="mini" type="default" @click="projectModule.showSelector">选择项目组</nut-button>
                        </view>
                        <basic-cascader v-model:visible="projectModule.show" v-model:options="projectModule.options"
                            :title-prefix="'当前项目组'" :current-value="formData.projectname"
                            @change="projectModule.onChange" />
                    </nut-form-item>
                    <!-- edit by qfx 20250226 prop="" ==> prop="bedName" 改为验证 bedName，支持手动输入和选择-->
                    <nut-form-item label="床号" prop="bedName" :required="!isHomeAddress" :rules="bedRules">
                        <view class="w-full flex justify-between items-center">
                            <nut-input v-model="formData.bedName" placeholder="请输入床号" type="text" />
                            <nut-button size="mini" type="default" @click="bedModule.showBed">选择床号</nut-button>
                        </view>
                        <nut-popup v-model:visible="bedModule.show" position="bottom">
                            <nut-picker :columns="bedModule.columns" title="选择床号" @cancel="bedModule.show = false"
                                @confirm="bedModule.confirm" />
                        </nut-popup>
                    </nut-form-item>

                    <nut-form-item label="默认地址" prop="isDefault">
                        <nut-switch v-model="formData.isDefault" @change="defaultChange"></nut-switch>
                    </nut-form-item>
                    <nut-cell>
                        <basic-button text="保存" class="mt-2" @on-click="submit" />
                    </nut-cell>
                </nut-form>
            </view>
        </view>
        <!-- <basic-map /> -->
    </basic-layout>
</template>

